package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.shopping.converter.CartItemConverter;
import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dal.persistence.ItemMapper;
import com.cskaoyan.shopping.dto.CartProductDto;
import com.cskaoyan.shopping.form.CartRequest;
import com.cskaoyan.shopping.form.CheckAllItemRequest;
import com.cskaoyan.shopping.service.ICartService;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @projectName: duolaimall
 * @package: com.cskaoyan.shopping.service.impl
 * @className: ICartServiceImpl
 * @author: 杨浩祥
 * @description: TODO
 * @date: 2022/10/25 20:31
 * @version: 1.0
 */
@Service
public class ICartServiceImpl implements ICartService {

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    CartItemConverter itemConverter;

    @Autowired
    RedissonClient redissonClient;


    // redis获取购物车map的关键字为"tb_cart" + userId,map键值对的key为itemId,值为CartProductDto


    /**
     * 获得购物车商品列表
     */
    @Override
    public List<CartProductDto> getCartListById(Long userId) {
        Map<String, CartProductDto> cartMap = redissonClient.getMap("tb_cart" + userId);
        //查询所有的商品信息
        Example example = new Example(Item.class);
        example.createCriteria().andEqualTo("status", 1);
        List<Item> items= itemMapper.selectByExample(example);

        List<CartProductDto> cartProductDtos=new LinkedList<>();
        for (Item item : items) {
            if (cartMap.containsKey(item.getId().toString())){
                CartProductDto cartProductDto = cartMap.get(item.getId().toString());
                cartProductDtos.add(cartProductDto);
            }
        }
        cartProductDtos = cartProductDtos.stream().sorted(Comparator.comparing(CartProductDto::getAddTime).reversed()).collect(Collectors.toList());
        // System.out.println(cartProductDtos);
        return cartProductDtos;
    }

    // 设置权限？？
    // 暂未处理参数可能大于库存的情况
    @Override
    public void addToCart(CartRequest request) {
        Item item = itemMapper.selectByPrimaryKey(request.getProductId());
        CartProductDto cartProductDto = itemConverter.item2Dto(item);
        cartProductDto.setChecked(request.getChecked());
        cartProductDto.setProductNum(request.getProductNum());
        cartProductDto.setAddTime(new Date());
        Map<String, CartProductDto> cartMap = redissonClient.getMap("tb_cart" + request.getUserId());
        CartProductDto cartProductDtoInRedis = cartMap.get(request.getProductId().toString());
        // System.out.println(cartProductDtoInRedis);
        if (cartProductDtoInRedis != null) {
            cartProductDto.setProductNum(cartProductDtoInRedis.getProductNum() + cartProductDto.getProductNum());
        }
        cartMap.put(request.getProductId().toString(), cartProductDto);
    }

    @Override
    public void updateCartNum(CartRequest request) {
        Map<String, CartProductDto> cartMap = redissonClient.getMap("tb_cart" + request.getUserId());
        CartProductDto cartProductDtoInRedis = cartMap.get(request.getProductId().toString());
        // System.out.println("前"+cartProductDtoInRedis);
        cartProductDtoInRedis.setProductNum(request.getProductNum());
        cartProductDtoInRedis.setChecked(request.getChecked());
        cartMap.put(request.getProductId().toString(), cartProductDtoInRedis);
        // System.out.println("后"+cartProductDtoInRedis);

    }
    /**
     * 选择购物车中的所有商品
     * @param request
     * @return
     */
    @Override
    public void checkAllCartItem(CheckAllItemRequest request) {
        Map<String, CartProductDto> cartMap = redissonClient.getMap("tb_cart" + request.getUserId());
        //查询所有的商品信息
        Example example = new Example(Item.class);
        example.createCriteria().andEqualTo("status", 1);
        List<Item> items= itemMapper.selectByExample(example);

        List<CartProductDto> cartProductDtos=new LinkedList<>();
        for (Item item : items) {
            if (cartMap.containsKey(item.getId().toString())){
                CartProductDto cartProductDto = cartMap.get(item.getId().toString());
                cartProductDto.setChecked(request.getChecked());
                cartMap.put(item.getId().toString(), cartProductDto);
            }
        }
    }

    @Override
    public void deleteCartItem(Long uid, Long itemId) {
        Map<String, CartProductDto> cartMap = redissonClient.getMap("tb_cart" + uid);
        cartMap.remove(itemId.toString());
    }

    @Override
    public void deleteCheckedItem(Long userId) {
        Map<String, CartProductDto> cartMap = redissonClient.getMap("tb_cart" + userId);
        for (Map.Entry<String, CartProductDto> entry : cartMap.entrySet()) {
            String itemId = entry.getKey();
            CartProductDto cartProductDto = entry.getValue();
            if ("true".equals(cartProductDto.getChecked())){
                cartMap.remove(itemId);
            }
        }
    }
}
